package com.yuejiekeji.photowall.configuration;


import com.yuejiekeji.photowall.common.BizException;
import com.yuejiekeji.photowall.common.Ret;
import com.yuejiekeji.photowall.util.HttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;


import java.util.Objects;

/**
 * 全局异常处理器
 */
@ControllerAdvice(basePackages = "com.yuejiekeji.shopping.controller")
@Slf4j
@RestController
public class GlobalExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public Ret handleThrowable(Throwable e, HttpServletRequest request) {
        String uri = request.getRequestURI();
        String params = HttpUtil.getRequestParams(request);
        String requestHeader = HttpUtil.getRequestHeader(request);
        try {
            if (e instanceof BizException bizException){
                log.error("请求[{}] params[{}] header[{}] error [{}}]",uri,params,requestHeader,bizException.getStackTrace()[0], bizException);
                if (!Objects.isNull(bizException.getErrorParams()) && bizException.getErrorParams().length > 0){
                    return Ret.error(bizException.getErrorCode(),bizException.getMessage());
                }else {
                    return Ret.error(bizException.getErrorCode());
                }
            }else {
                log.error("请求[{}] params[{}] header[{}] error [{}]",uri,params,requestHeader,e.getStackTrace()[0], e);
                return Ret.error();
            }

        }catch (Exception exception){
            log.error("请求[{}}] params[{}] header[{}] error [{}]",uri,params,requestHeader,exception.getStackTrace()[0], exception);
            return Ret.error();
        }



    }

}
